package com.margo.project.shiro.distributed;

import java.io.Serializable;
import java.util.Collection;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

public class RedisSessionDAO extends AbstractSessionDAO{
	
	private final static String SHIRO_SESSION_KEY="shiro-session";
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private RedisTemplate redisTemplate;

	public RedisTemplate getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	@Override
	public void update(Session session) throws UnknownSessionException {
		// TODO Auto-generated method stub
	}

	@Override
	public void delete(Session session) {
		if(session == null || session.getId() == null){
			logger.error("session or session id is null");
			return;
		}
		redisTemplate.opsForHash().put(SHIRO_SESSION_KEY, session.getId(), session);
		
	}

	@Override
	public Collection<Session> getActiveSessions() {
		return redisTemplate.opsForHash().values(SHIRO_SESSION_KEY);
	}

	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = this.generateSessionId(session);  
        this.assignSessionId(session, sessionId);
        logger.info("doCreate:"+sessionId);
		redisTemplate.opsForHash().put(SHIRO_SESSION_KEY, session.getId(), session);
		return session.getId();
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		logger.info("doReadSession:"+sessionId);
		// TODO Auto-generated method stub
		return (Session) redisTemplate.opsForHash().get(SHIRO_SESSION_KEY,sessionId);
	}

}
